import React, { Component } from 'react'
import styles from './index.module.scss'
import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Modal,
  Input,
  Space,
  Upload,
  message,
  Spin
} from 'antd'
import { Link } from 'react-router-dom'
import ArticleChannels from '../../components/ArticleChannels'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import Radio from 'antd/es/radio/radio'
import { CloudUploadOutlined } from '@ant-design/icons'
import { baseURL } from '../../utils/request'
import { addArticle, ArticleInfo, editArticle } from '../../api/article'

export default class ArticlePublish extends Component {
  constructor(props) {
    super(props)
    this.state = {
      type: 1,
      previewVisible: false,
      previewImage: '',
      previewTitle: '',
      fileList1: [],
      fileList3: [],
      imgValidateStatus: '',
      imgHelp: ''
    }
    this.formRef = React.createRef()
  }

  componentDidMount() {
    this.initEditing()
  }

  async initEditing() {
    // 编辑的时候的id
    const { EditId } = this.state
    if (EditId) {
      const {
        data: { title, content, cover, channel_id }
      } = await ArticleInfo(EditId)
      const { type } = cover
      // 给上传图片组件默认值
      this.setState({
        ['fileList' + type]: cover.images.map((item, index) => {
          return {
            uid: index,
            url: item
          }
        }),
        type
      })
      const fromEditData = {
        title,
        content,
        type,
        channel_id
      }
      this.formRef.current.setFieldsValue(fromEditData)
    }
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.state.type === 0 && this.state.imgValidateStatus !== '') {
      this.setState({
        imgValidateStatus: '',
        imgHelp: ``
      })
    }
  }

  render() {
    const {
      type,
      imgValidateStatus,
      imgHelp,
      previewImage,
      previewVisible,
      previewTitle,
      EditId
    } = this.state
    const fileList = this.state['fileList' + type]
    return (
      <div className={styles['ArticlePublish']}>
        <Card
          title={
            <Breadcrumb separator='>'>
              <Breadcrumb.Item>
                <Link to={'/home'}>首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {EditId ? '文章编辑' : '文章发布'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }>
          <Form
            ref={this.formRef}
            onFinish={this.onFinish}
            labelCol={{ span: 4 }}
            initialValues={{ content: '', type: type }}>
            <Form.Item
              name={'title'}
              label={'标题'}
              rules={[{ required: true, message: '请输入标题' }]}>
              <Input style={{ width: 400 }}></Input>
            </Form.Item>
            <Form.Item
              label={'频道'}
              name={'channel_id'}
              rules={[{ required: true, message: '请选择频道' }]}>
              <ArticleChannels width={400} />
            </Form.Item>
            <Form.Item
              label={'封面'}
              validateStatus={imgValidateStatus}
              name={'type'}
              required={true}
              style={{ marginBottom: 0 }}
              help={imgHelp}>
              <Radio.Group
                value={type}
                onChange={(e) =>
                  this.setState({
                    type: e.target.value
                  })
                }>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {/*文件上传*/}
            {!!type && (
              <Form.Item label={' '} colon={false} name={'image'}>
                <Upload
                  listType='picture-card'
                  name={'image'}
                  fileList={fileList}
                  action={`${baseURL}upload`}
                  onPreview={this.handlePreview}
                  onCancel={this.handleCancel}
                  onChange={this.handleUploadImage}
                  beforeUpload={this.beforeUpload}
                  key={'fileList' + type}>
                  {fileList.length < type && (
                    <CloudUploadOutlined style={{ fontSize: '20px' }} />
                  )}
                </Upload>
              </Form.Item>
            )}
            <Form.Item
              label={'内容'}
              name={'content'}
              rules={[{ required: true, message: '请输入文章类容' }]}>
              <ReactQuill theme='snow' placeholder={'请输入文章内容'} />
            </Form.Item>
            <Form.Item label={' '} colon={false}>
              <Space>
                <Button
                  type={'primary'}
                  htmlType={'submit'}
                  onClick={this.handleSubmit}>
                  {EditId ? '文章编辑' : '文章发布'}
                </Button>

                <Button onClick={this.handlePublishDraft}>发布草稿</Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}>
          <img alt='example' style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    )
  }

  // 修改文章
  handleEdit = (value) => {
    console.log(value)
  }

  beforeUpload = (file) => {
    if (file.size / 1024 / 1024 > 2) {
      message.warn('文件大小不能超过2MB')
      return Upload.LIST_IGNORE
    } else if (!['image/jpeg', 'image/png'].includes(file.type)) {
      message.warn('文件类型应该为jpg或png')
      return Upload.LIST_IGNORE
    }

    return true
  }

  handlePreview = async (file) => {
    this.setState({
      previewImage: file.url || file.response.data.url,
      previewVisible: true,
      previewTitle:
        file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
    })
  }

  handleCancel = () => this.setState({ previewVisible: false })

  handleUploadImage = ({ file, fileList }) => {
    if (file.status === 'error') {
      message.error('图片上传失败')
      this.setState({
        ['fileList' + this.state.type]: fileList.filter(
          (item) => item.status !== 'error'
        )
      })
      return
    }
    this.setState(
      {
        ['fileList' + this.state.type]: fileList
      },
      () => {
        const { type } = this.state
        if (type && type === this.state['fileList' + type].length) {
          this.setState({
            imgValidateStatus: '',
            imgHelp: ``
          })
        }
      }
    )
  }
  handleSubmit = () => {
    const { type } = this.state
    if (type && type > this.state['fileList' + type].length) {
      this.setState({
        imgValidateStatus: 'error',
        imgHelp: `上传封面小于${type}张`
      })
    } else {
      this.setState({
        imgValidateStatus: '',
        imgHelp: ``
      })
    }
  }

  onFinish = async (value, draft = false) => {
    const newFileList = this.state.type
      ? this.state['fileList' + this.state.type].map(
          (item) => item.url || item.response.data.url
        )
      : []
    value.cover = {
      type: value.type,
      images: newFileList
    }
    delete value.type
    delete value.image
    if (this.state.imgValidateStatus.length !== 0) return
    if (this.state.EditId) {
      await editArticle(this.state.EditId, value, draft)
      message.success('编辑成功')
    } else {
      await addArticle(value, draft)
      message.success('发布成功')
    }

    this.props.history.push('/home/articleList')
  }

  handlePublishDraft = async () => {
    this.handleSubmit()
    try {
      const value = await this.formRef.current.validateFields()
      this.onFinish(value, true)
    } catch (e) {}
    // const value =
  }
}
